//
//  PraiseViewController.m
//  SXH
//
//  Created by Jack on 15/8/31.
//  Copyright (c) 2015年 lyss. All rights reserved.
//

#import "PraiseViewController.h"
#import "PraiseTableViewCell.h"
#import "YYAnimationIndicator.h"
#import "CommonService.h"
#import "UIButton+WebCache.h"
#import "FindDetailViewController.h"
#import "FindMeTableViewCell.h"
#import "UIImageView+AFNetworking.h"
#import "FindEntity.h"
#import "UserEntity.h"
#import "MJRefresh.h"
@interface PraiseViewController ()<FindMeDelegate>
{
    YYAnimationIndicator *indicator;
    int page;
    MJRefreshHeaderView *_header;
    MJRefreshFooterView *_footer;
}

@property (nonatomic, strong) NSMutableArray *mutableArrayPraise;
@property (nonatomic, strong) IBOutlet UITableView *tableViewPraise;
@property (weak, nonatomic) IBOutlet UILabel *titleLab;

@end

@implementation PraiseViewController

@synthesize mutableArrayPraise, tableViewPraise;
@synthesize userId;
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = @"赞过";
    if (self.titleStr.length > 0) {
        _titleLab.text = self.titleStr;
    } else {
        _titleLab.text = self.title;
    }
    
    if (is_IOS_7) {
        self.edgesForExtendedLayout = UIRectEdgeNone;
        self.extendedLayoutIncludesOpaqueBars = NO;
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    
    mutableArrayPraise = [[NSMutableArray alloc] init];
    
    [self addHeader];
    [self addFooter];
    [self getUserInfo];
    
}

#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    return [mutableArrayPraise count]/3 + ([mutableArrayPraise count]%3<1?0:1);
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *couponTableViewCellIdentifier=@"FindMeTableViewCell";
    FindMeTableViewCell *cell = (FindMeTableViewCell *)[tableView dequeueReusableCellWithIdentifier:couponTableViewCellIdentifier];
    if (cell == nil) {
        NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"FindMeTableViewCell" owner:self options:nil];
        cell = [array objectAtIndex:0];
        cell.findMeDelegate = self;
    }
    cell.backgroundColor = [UIColor clearColor];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    if (indexPath.row*3 < [mutableArrayPraise count]) {
        FindEntity *entity = [mutableArrayPraise objectAtIndex:indexPath.row*3];
        
        NSArray *array = [entity.album_thumb componentsSeparatedByString:@","];
        
        NSLog(@"array1:%@",array);
        
        if (array != nil && [array count] > 0) {
            NSString *imageUrl = [array objectAtIndex:0];
            [cell.imgleft setImageWithURL:[NSURL URLWithString:imageUrl]];
        }
        cell.btnLeft.tag = indexPath.row*3;
        cell.btnLeft.hidden = NO;
    }
    
    if (indexPath.row*3 + 1 < [mutableArrayPraise count]) {
        FindEntity *entity = [mutableArrayPraise objectAtIndex:indexPath.row*3 + 1];
        NSArray *array = [entity.album_thumb componentsSeparatedByString:@","];
        
        NSLog(@"array2:%@",array);
        
        if (array != nil && [array count] > 0) {
            NSString *imageUrl = [array objectAtIndex:0];
            [cell.imgmiddle setImageWithURL:[NSURL URLWithString:imageUrl]];
        }
        cell.btnMiddle.tag = indexPath.row*3 + 1;
        cell.btnMiddle.hidden = NO;
    }
    
    if (indexPath.row*3 + 2 < [mutableArrayPraise count]) {
        FindEntity *entity = [mutableArrayPraise objectAtIndex:indexPath.row*3 + 2];
        NSArray *array = [entity.album_thumb componentsSeparatedByString:@","];
        if (array != nil && [array count] > 0) {
            NSString *imageUrl = [array objectAtIndex:0];
            [cell.imgright setImageWithURL:[NSURL URLWithString:imageUrl]];
        }
        cell.btnRight.tag = indexPath.row*3 + 2;
        
        cell.btnRight.hidden = NO;
    }
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 104.f/320.f*SCREEN_WIDTH;
}

#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
}

- (void)findMeButtonAction:(NSInteger) tag {
    FindEntity *entity = [mutableArrayPraise objectAtIndex:tag];
    
    FindDetailViewController *vc = [[FindDetailViewController alloc] init];
    vc.findEntity = entity;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void) getPraiseData:(int)apage RefreshView:(MJRefreshBaseView*)refreshView
{

    NSString *Nopage = [NSString stringWithFormat:@"%d",apage];
    CommonService *service = [[CommonService alloc] init];
    NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:
                           userId, @"user_id",
                           Nopage, @"page",
                           @"20", @"limit",nil];
    
    [service getNetWorkData:param
                       Path:USER_QUERY_Praise
                  Successed:^(id entity) {
                      NSDictionary *dic = (NSDictionary *)entity;
                      
                      NSArray *array = [dic objectForKey:@"rows"];
                      if (apage == 1) {
                          [mutableArrayPraise removeAllObjects];
                      }
                      for (NSDictionary* attributes in array) {
                          FindEntity *entity = [[FindEntity alloc] init];
                          entity = [entity initWithAttributes:attributes];
                          [mutableArrayPraise addObject:entity];
                      }
                      [self doneWithView:refreshView];
                      
                  } Failed:^(NSInteger errorCode, NSString *message) {
                      DebugLog(@"%@", message);
                      [self doneWithView:refreshView];
                  }];
}

- (void) getUserInfo {
    
    CommonService *service = [[CommonService alloc] init];
    NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:
                           userId, @"userid",nil];
    
    [service getNetWorkData:param
                       Path:USER_QUERY_BY_ID
                  Successed:^(id entity) {
                      NSDictionary *dic = (NSDictionary *)entity;
                      
                      NSDictionary *dic_user = [dic objectForKey:@"row"];
                      
                      UserEntity *userEntity = [[UserEntity alloc] init];
                      userEntity = [userEntity initWithAttributes:dic_user];
                      
                  } Failed:^(NSInteger errorCode, NSString *message) {
                      DebugLog(@"%@", message);
                  }];
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:@"PraiseViewController"];
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:@"PraiseViewController"];
}


- (void)addFooter
{
    //__unsafe_unretained OAAnnoViewController *vc = self;
    MJRefreshFooterView *footer = [MJRefreshFooterView footer];
    footer.scrollView = self.tableViewPraise;
    footer.beginRefreshingBlock = ^(MJRefreshBaseView *refreshView) {
        
        ++page;
        [self getPraiseData:page RefreshView:refreshView];
        
        NSLog(@"%@----开始进入刷新状态", refreshView.class);
    };
    _footer = footer;
}

- (void)addHeader
{
    //__unsafe_unretained OAAnnoViewController *vc = self;
    MJRefreshHeaderView *header = [MJRefreshHeaderView header];
    header.scrollView = self.tableViewPraise;
    
    header.beginRefreshingBlock = ^(MJRefreshBaseView *refreshView) {
        // 进入刷新状态就会回调这个Block
        [self getPraiseData:1 RefreshView:refreshView];
        NSLog(@"%@----开始进入刷新状态", refreshView.class);
    };
    header.endStateChangeBlock = ^(MJRefreshBaseView *refreshView) {
        // 刷新完毕就会回调这个Block
        NSLog(@"%@----刷新完毕", refreshView.class);
    };
    header.refreshStateChangeBlock = ^(MJRefreshBaseView *refreshView, MJRefreshState state) {
        // 控件的刷新状态切换了就会调用这个block
        switch (state) {
            case MJRefreshStateNormal:
                NSLog(@"%@----切换到：普通状态", refreshView.class);
                break;
            case MJRefreshStatePulling:
                NSLog(@"%@----切换到：松开即可刷新的状态", refreshView.class);
                break;
            case MJRefreshStateRefreshing:
                NSLog(@"%@----切换到：正在刷新状态", refreshView.class);
                break;
            default:
                break;
        }
    };
    [header beginRefreshing];
    _header = header;
}

- (void)doneWithView:(MJRefreshBaseView *)refreshView
{
    // 刷新表格
    [self.tableViewPraise reloadData];
    // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
    [refreshView endRefreshing];
}
@end
